package com.ruoyi.web.controller.admin.newSystem;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.session.SaSession;
import com.ruoyi.admin.domain.SystemUserLogin;
import com.ruoyi.admin.service.ISystemUserLoginService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.AdminUserDO;
import com.ruoyi.common.core.domain.entity.RoleDO;
import com.ruoyi.common.utils.StpSystemUtil;
import com.ruoyi.newSystem.bean.input.AuthSmsLoginReqVO;
import com.ruoyi.newSystem.bean.input.AuthSmsSendReqVO;
import com.ruoyi.newSystem.service.AdminUserService;
import com.ruoyi.newSystem.service.RoleService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static com.ruoyi.common.core.domain.AjaxResult.success;


/**
 * The type Auth controller.
 */
@Tag(name = "管理后台 - 认证")
@RestController
@RequestMapping("/newSystem/auth")
@Validated
@Slf4j
public class AdminUserController {

    @Resource
    private AdminUserService adminUserService;
    @Resource
    private RoleService roleService;
    @Resource
    private ISystemUserLoginService systemUserLoginService;


//    @GetMapping("/getDataScope")
//    public AjaxResult getDataScope() {
//        StringBuilder filterBuilder = new StringBuilder("id > 0");
//        if (!StpSystemUtil.isAdmin()) {
//            List<String> dataScope = roleService.getDataScope();
//            List<Tree<String>> trees = llmFaqCategoryService.treeFaqCategory();
//            List<Tree<String>> collect = trees.stream().filter(item -> dataScope.contains(item.getId())).collect(Collectors.toList());
//            List<String> strings = new ArrayList<>();
//            collect.forEach(item -> {
//                strings.addAll(TreeUtils.getAllNodeIds(item));
//            });
//            List<Long> elementIds = llmFaqMapper.selectElementIdLongs(strings);
//            if (elementIds.isEmpty()) {
//                return AjaxResult.error();
//            }
//            filterBuilder.append(" and id in ").append(JSONArray.toJSONString(elementIds));
//        }
//        return AjaxResult.success(filterBuilder.toString());
//
//    }


    /**
     * Logout common result.
     *
     * @return the common result
     */
    @PostMapping("/logout")
    @SaIgnore
    public AjaxResult logout() {
        try {
            if (!StpSystemUtil.isLogin()) {
                log.info("用户未登录或token已过期，直接返回登出成功");
                return success(true);
            }

            // 获取会话并登出
            SaSession sessionByLoginId = StpSystemUtil.getSessionByLoginId(StpSystemUtil.getLoginId());
            sessionByLoginId.logout();
            StpSystemUtil.logout(StpSystemUtil.getLoginId(), StpSystemUtil.TYPE);
        } catch (Exception exception) {
            log.warn("退出登陆失败", exception);
            // 即使发生异常，也返回成功，因为用户只关心是否已退出登录状态
        }
        return success(true);
    }

    /**
     * Refresh token common result.
     *
     * @param refreshToken the refresh token
     * @return the common result
     */
    @PostMapping("/refresh-token")
    @SaIgnore
    public AjaxResult refreshToken(@RequestParam("refreshToken") String refreshToken) {
        return success(null);
    }


    /**
     * Sms login common result.
     *
     * @param reqVO the req vo
     * @return the common result
     */
    @PostMapping("/sms-login")
    @SaIgnore
    public AjaxResult smsLogin(@RequestBody @Valid AuthSmsLoginReqVO reqVO) {
        return success(null);
    }

    /**
     * Send login sms code common result.
     *
     * @param reqVO the req vo
     * @return the common result
     */
    @PostMapping("/send-sms-code")
    @SaIgnore
    public AjaxResult sendLoginSmsCode(@RequestBody @Valid AuthSmsSendReqVO reqVO) {
        return success(true);
    }


    @GetMapping("/exportLogin")
    public void exportLogin(HttpServletResponse httpServletResponse) throws IOException {
        List<SystemUserLogin> allLogin = systemUserLoginService.getAllLogin();

        Workbook workbook = new XSSFWorkbook();


        Sheet sheet = workbook.createSheet();
        Row row1 = sheet.createRow(0);
        row1.createCell(0).setCellValue("登录ip");
        row1.createCell(1).setCellValue("登录时间");
        row1.createCell(2).setCellValue("用户名");
        row1.createCell(3).setCellValue("账号");

        for (int i = 0; i < allLogin.size(); i++) {
            row1 = sheet.createRow(i + 1);
            row1.createCell(0).setCellValue(allLogin.get(i).getLoginIp());
            row1.createCell(1).setCellValue(allLogin.get(i).getLoginTime());
            row1.createCell(2).setCellValue(allLogin.get(i).getLoginUser());
            row1.createCell(3).setCellValue(allLogin.get(i).getUserCode());
        }


        httpServletResponse.setContentType("application/x-msdownload");
        String encode = URLEncoder.encode("登录日志.xlsx", StandardCharsets.UTF_8);
        httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + encode);
        workbook.write(httpServletResponse.getOutputStream());
        workbook.close();
    }

    /**
     * Gets permission info.
     *
     * @return the permission info
     */
    @GetMapping("/getDataSetPermission")
    public AjaxResult getDataSetPermission(@RequestParam("roleId") Long roleId) {

        RoleDO role1 = roleService.getRole(roleId);

        // 2. 拼接结果返回
        return AjaxResult.success(role1.getDataScopeAccessIds());
    }


    @GetMapping("/getUserByUserId")
    public AjaxResult getUserByUserId() {
        Long loginIdAsLong = StpSystemUtil.getLoginIdAsLong();
        AdminUserDO user = adminUserService.getUserByUserId(loginIdAsLong);
        return AjaxResult.success(user);
    }

}
